package handler

import (
	"art-man-sys/cache"
	"art-man-sys/models"
	"art-man-sys/pkg"
	"github.com/gin-gonic/gin"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}

	redis_key := "login_err_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()

	if errCount > 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "错误3次密码,禁止登录",
		})
		return
	}
	var user models.User
	err := models.DB.Where("username= ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名不存在",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名存在",
		})
		return
	}
	if pkg.Md5str(password) != user.Password {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次,封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "登录失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": "登录成功",
	})
	return

}
